<?php 
class product_plugin_bestseller extends abstract_product_plugin {

    public function getBestSellerProducts($limit) { 
        
        $query = $this->pdo->prepare("
            SELECT 
            p.*, 
            pd.name AS name, 
            op.product_id, 
            COUNT(*) AS total  
            FROM " . $this->db_prefix . "order_product op 
            INNER JOIN " . $this->db_prefix . "product p 
            ON (op.product_id = p.product_id) 
            LEFT JOIN " . $this->db_prefix . "order o 
            ON (op.order_id = o.order_id) 
            LEFT JOIN " . $this->db_prefix . "product_description pd 
            ON (p.product_id = pd.product_id) 
            LEFT JOIN " . $this->db_prefix . "product_to_store p2s 
            ON (p.product_id = p2s.product_id) 
            WHERE o.order_status_id > '0' 
            AND p.status = '1' 
            AND p.date_available <= NOW() 
            AND p2s.store_id = :store_id  
            GROUP BY op.product_id 
            ORDER BY total DESC LIMIT :limit");
        
        $limit = (int) $limit; 
        $query->bindParam(':limit', $limit, PDO::PARAM_INT);
        $query->bindParam(':store_id', $this->site_id, PDO::PARAM_INT);
        $query->execute();

        $product_data = array();

        while ($product = $query->fetchObject('class_product')) {
            $product_data[$product->get_id()] = $product;	
        }

        return $product_data;
    }
}
